package com.yixiang.np.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.yixiang.np.constant.GlobalConstant;
import com.yixiang.np.dao.OrganizationDao;
import com.yixiang.np.dao.UserDao;
import com.yixiang.np.model.PageFilter;
import com.yixiang.np.model.SessionInfo;
import com.yixiang.np.model.po.Dictionary;
import com.yixiang.np.model.po.Organization;
import com.yixiang.np.model.po.User;
import com.yixiang.np.model.vo.RegVo;
import com.yixiang.np.service.UserServiceI;
import com.yixiang.np.utils.MD5Util;



 

/**
 * Created by LiZhengYong on 2016/6/16.
 */
@Service
@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
public class UserServiceImpl implements UserServiceI {

    private Logger logger = Logger.getLogger(UserServiceImpl.class);
    
    @Autowired
	private UserDao userDao;
	
    @Autowired
	private OrganizationDao organ_dao;

	@Override
	public void add(User u) {
		u.setState(GlobalConstant.ENABLE);
		u.setPassword(MD5Util.md5(u.getPassword()));
		u.setCreatedatetime(new Date());
		u.setIsdefault(1);
		Long id = userDao.add(u);
		if (u.getRoleIds() != null) {
			Map<String, Object> params = new HashMap<String, Object>();
			for (String rid : u.getRoleIds().split(",")) {
				params.put("role_id", rid);
				params.put("user_id", u.getId());
				userDao.addUserRole(params);
			}
		} 
	}

	@Override
	public List<User> dataGrid(User user, PageFilter ph) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(user.getOrganizationId() != null){
			params.put("organization_id", user.getOrganizationId());
			params.put("usertype", user.getUsertype());
		}
		List<User> l = userDao.findAll(params);
		return l;
	}

	@Override
	public Long count(User user, PageFilter ph) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(user.getOrganizationId() != null){
			params.put("organization_id", user.getOrganizationId());
			params.put("usertype", user.getUsertype());
		}
		return userDao.count(params);
	}

	@Override
	public void delete(Long id) {
		userDao.deleteUserRole(id);
		userDao.delete(id);
	}

	@Override
	public void edit(User user) {
		User u = userDao.get(user.getId());
		userDao.deleteUserRole(user.getId());
		if(user.getPassword()==null || "".equals(user.getPassword())){
			user.setPassword(u.getPassword());
		}else{
			user.setPassword(MD5Util.md5(user.getPassword()));
		}
		user.setIsdefault(1);
		user.setState(u.getState());
		userDao.edit(user);
		if (user.getRoleIds() != null) {
			Map<String, Object> params = new HashMap<String, Object>();
			for (String rid : user.getRoleIds().split(",")) {
				params.put("role_id", rid);
				params.put("user_id", user.getId());
				userDao.addUserRole(params);
			}
		} 
	}

	@Override
	public User get(Long id) {
		List<String> list = userDao.getRoles(id);
		User user = userDao.get(id);
		String roleids = "";
		if(list!=null && list.size()>0){
			boolean b = false;
			for (String tr : list) {
				if (b) {
					roleids += ",";
				} else {
					b = true;
				}
				roleids += tr;
			} 
			user.setRoleIds(roleids);
		}
		return user;
	}

	@Override
	public User login(User user) {
		user.setPassword(MD5Util.md5(user.getPassword()));
		User t = userDao.login(user);
		if (t != null) {
			return t;
		}
		return null;
	}

	@Override
	public List<String> resourceList(Long id) {
		List<String> resourceList = new ArrayList<String>();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", id);
		resourceList = userDao.resourceList(params);
		 
		return resourceList;
	}

	@Override
	public boolean editUserPwd(SessionInfo sessionInfo, String oldPwd, String pwd) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", sessionInfo.getId());
		params.put("password", MD5Util.md5(pwd));
		userDao.editUserPwd(params);
		return false;
	}

	@Override
	public User getByLoginName(User user) {
		User t = userDao.getByLoginName(user.getLoginname());
		if(t!=null){
			return t;
		}else{
			return null;
		}
	}
	public List<Dictionary> combox(String roleId) {
		List<Dictionary> ld = new ArrayList<Dictionary>();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("role_id", roleId);
		List<User>  lt = userDao.findByRole(params);
		if(lt!=null&&lt.size()>0){
			 for (int i = 0; i < lt.size(); i++) {
				 Dictionary d = new Dictionary();
				 d.setId(lt.get(i).getId());
				 d.setText(lt.get(i).getName());
				 ld.add(d);
			}
		 }
		return ld;
	}
	
	private @Value("${purchaser}") String purchaser;
	private @Value("${purchaser.admin.role}") String purchaserRole;
	private @Value("${notaudit.role}") String notauditRole;
	@Override
	public void regUser(RegVo reg) {
		//保存部门信息
		Organization org = new Organization();
		org.setName(reg.getCompany());
		org.setCode("");
		org.setSeq(0);
		org.setIcon("icon_org");
		org.setProv(reg.getProv());
		org.setCity(reg.getCity());
		org.setMobile(reg.getMobile());
		org.setTelphone(reg.getTelphone());
		org.setContact(reg.getContacts());
		org.setAddress(reg.getLocation());
		org.setPid(Long.parseLong(purchaser));
		org.setCreatedatetime(new Date());
		org.setBankName(reg.getBankName());
		org.setBankCard(reg.getBankCard());
		org.setBankUser(reg.getBankUser());
		org.setOrgType(Organization.PURCHASE);
		org.setZzPath(reg.getZzPath());
		organ_dao.add(org);
		//保存用户信息
		User u = new User();
		u.setLoginname(reg.getUsername());
		u.setName(reg.getNickname());
		u.setMobile(reg.getMobile());
		u.setEmail(reg.getMail());
		u.setOrganizationId(org.getId());
		u.setState(GlobalConstant.TOAUDIT);
		u.setPassword(MD5Util.md5(reg.getPwd()));
		u.setSex(0);
		u.setUsertype(1);
		u.setCreatedatetime(new Date());
		u.setIsdefault(1);
		Long id = userDao.add(u);
		//保存用户角色信息
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("role_id", notauditRole);
		params.put("user_id", u.getId());
		userDao.addUserRole(params);
	}
	private @Value("${supplier}") String supplier;
	private @Value("${supplier.admin.role}") String supplierRole;
	@Override
	public void regSupplierUser(RegVo reg) {
		//保存部门信息
		Organization org = new Organization();
		org.setName(reg.getCompany());
		org.setCode("");
		org.setSeq(0);
		org.setIcon("icon_org");
		org.setProv(reg.getProv());
		org.setCity(reg.getCity());
		org.setMobile(reg.getMobile());
		org.setTelphone(reg.getTelphone());
		org.setContact(reg.getContacts());
		org.setAddress(reg.getLocation());
		org.setPid(Long.parseLong(supplier));
		org.setCreatedatetime(new Date());
		org.setBankName(reg.getBankName());
		org.setBankCard(reg.getBankCard());
		org.setBankUser(reg.getBankUser());
		org.setOrgType(Organization.SUPPLIER);
		org.setKeepTimeCharter(Organization.KEEPTIMECHARTER);
		org.setKeepTimeSingle(Organization.KEEPTIMESINGLE);
		org.setCreditOver(Organization.CREDITOVER);
		org.setCreditTime(Organization.CREDITTIME);
		org.setCharges(Organization.CHARGES);
		organ_dao.add(org);
		//保存用户信息
		User u = new User();
		u.setLoginname(reg.getUsername());
		u.setName(reg.getNickname());
		u.setMobile(reg.getMobile());
		u.setEmail(reg.getMail());
		u.setOrganizationId(org.getId());
		u.setState(GlobalConstant.ENABLE);
		u.setPassword(MD5Util.md5(reg.getPwd()));
		u.setSex(0);
		u.setUsertype(1);
		u.setCreatedatetime(new Date());
		u.setIsdefault(1);
		Long id = userDao.add(u);
		//保存用户角色信息
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("role_id", supplierRole);
		params.put("user_id", u.getId());
		userDao.addUserRole(params);
	}
	private @Value("${purchaser.operator.role}") String purchaserOperator;
	private @Value("${supplier.operator.role}") String supplierOperator;
	@Override
	public void operatorAdd(RegVo reg, Long orgId) {
		//获取组织信息
		Organization org = organ_dao.get(orgId);
		//保存用户信息
		User u = new User();
		u.setLoginname(reg.getUsername());
		u.setName(reg.getNickname());
		u.setMobile(reg.getMobile());
		u.setEmail(reg.getMail());
		u.setOrganizationId(orgId);
		u.setState(GlobalConstant.ENABLE);
		u.setPassword(MD5Util.md5(reg.getPwd()));
		u.setSex(0);
		u.setUsertype(2);
		u.setCreatedatetime(new Date());
		u.setIsdefault(1);
		Long id = userDao.add(u);
		//保存用户角色信息
		Map<String, Object> params = new HashMap<String, Object>();
		if(org.getPid().toString().equals(supplier)){
			params.put("role_id", supplierOperator);
		}else if(org.getPid().toString().equals(purchaser)){
			params.put("role_id", purchaserOperator);
		}
		params.put("user_id", u.getId());
		userDao.addUserRole(params);
	}

	@Override
	public void resetPwd(String id, String password) {
		userDao.resetPwd(id, MD5Util.md5(password));
	}

	@Override
	public int getOperatorCountByOrg(Long orgId) {
		return userDao.getOperatorCountByOrg(orgId);
	}

	@Override
	public List<User> getUserByOrgid(Long orgId) {
		return userDao.getUserByOrgid(orgId);
	}

	@Override
	public List<RegVo> selectNoAudit(String username,String nickname,
									 String company,String contact,
									 Integer state,Integer ownerId) {
		return userDao.selectNoAudit(username,nickname,
				company,contact,
				state,ownerId);
	}

	public void auditSucess(Integer id,Integer state,String remark) {
		//如果审核通过则保存采购商角色否则维持原来的状态
		if(state.equals(0)){
			//保存用户角色信息
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("role_id", purchaserRole);
			params.put("user_id", id);
			userDao.addUserRole(params);
		}
		userDao.auditSucess(id,state,remark);
	}

	@Override
	public RegVo selectInfoById(Integer id) {
		return userDao.selectInfoById(id);
	}

}
